﻿using System;
using NORM.Entity;
using NORM.SQLObject;

namespace NORM
{
    public static class ExtensionEntity
    {
        public static TableField produceTableField(this NORM.Entity.EntityBase entity, string Field)
        {
            TableField tf = new TableField();
            tf.Entity = entity;
            tf.Field = Field;
            return tf;
        }

        public static object getPropertyItem(this NORM.Entity.EntityBase entity, int index)
        {
            string[] items = entity.Properties;
            return CacheProperties.cacheInstance.GetProperty(entity.GetType(), items[index]).GetValue(entity,null);
        }

        public static bool setPropertyItem(this NORM.Entity.EntityBase entity, TableField Item)
        {
            Type _type = entity.GetType();
            System.Reflection.PropertyInfo pi = CacheProperties.cacheInstance.GetProperty(_type, Item.Field);
            if (pi == null)
                return false;

            if (!pi.DeclaringType.Equals(Item.FieldType))
                return false;

            pi.SetValue(entity, Item.FieldValue, null);

            return true;
        }

        public static T produceItem<T>(this NORM.Entity.EntityBase entity, object PropertyName)
        {
            T t = default(T);

            object value = CacheProperties.cacheInstance
                .GetProperty(entity.GetType(), PropertyName.ToString()).GetValue(entity, null);

            if (typeof(T).FullName.Equals("NORM.Entity.Condition"))
            {
                t = (T)Activator.CreateInstance(typeof(T));                
                CacheProperties<T>.cacheInstance.GetProperty("Value").SetValue(t, value, null);
                CacheProperties<T>.cacheInstance.GetProperty("Field").SetValue(t, PropertyName.ToString(), null);
            }
            else if (typeof(T).FullName.Equals("NORM.Entity.TableField"))
            {
                t = (T)Activator.CreateInstance(typeof(T));                 
                if (value != null)
                    CacheProperties<T>.cacheInstance.GetProperty("FieldType").SetValue(t, value.GetType(), null);
                CacheProperties<T>.cacheInstance.GetProperty("Entity").SetValue(t, entity, null);
                CacheProperties<T>.cacheInstance.GetProperty("Field").SetValue(t, PropertyName.ToString(), null);
            }

            CacheProperties<T>.cacheInstance.Dispose();

            return t;
        }

    } 
}
